/**
 * 表格肩部按钮click事件
 */
import { ajax, formDownload, getMultiLang } from 'nc-lightapp-front'
import requestApi from '../requestApi'
import { getExcelImportConfig } from "../ExcelImportUtil"
import { showWarningDialog } from '../../../../../scmpub/scmpub/pub/tool/messageUtil'
import { beforeUpdatePage, updatePage } from 'ssccommon/utils/updatePage'
import { updataFormData, updatacardTableData } from 'ssccommon/utils/changePageData'

const areaBtnAction = window.presetVar.areaBtnAction
const statusVar = window.presetVar.status
const bodys = window.presetVar.body

function tableButtonClick (funcs = {}) {
    //_Add 覆盖默认调用函数
    return function () {
        setImportConfig(this.props)//导入按钮，注册导入事件
        return {
            ...funcs,
            //分摊页签增行回调
            ['er_cshare_detail_Add']: {
                afterClick: () => {
                    console.log('分摊页签增行后事件')
                    const moudleid = 'er_cshare_detail'
                    let props = this.props
                    let rowIndex = props.cardTable.getAllRows(moudleid).length - 1
                    props.cardTable.focusRowByIndex(moudleid, rowIndex)

                    let rowvalue = props.cardTable.getRowsByIndexs(moudleid, rowIndex)[0].values
                    console.log(JSON.stringify(rowvalue))

                    // 承担金额字段新增行时默认回写0, 用户合计计算
                    const scale = rowvalue.assume_amount.scale || 2
                    props.cardTable.setValByKeyAndIndex(moudleid, rowIndex, 'assume_amount', { //默认不合计的解决办法
                        value: (0.0).toFixed(scale),
                        scale: scale,
                        display: (0.0).toFixed(scale)
                    })


                    //补充一些默认值的逻辑，拉单生成的分摊明细，不会带默认值
                    let assume_org = rowvalue['assume_org']
                    let assume_dept = rowvalue['assume_dept']
                    let bzbm = rowvalue['bzbm']

                    let resacostcenter = props.form.getFormItemsValue(window.presetVar.head.head1, 'pk_resacostcenter')
                    props.cardTable.setValByKeyAndIndex(moudleid, rowIndex, 'pk_resacostcenter', resacostcenter)
                    let pcorg = props.form.getFormItemsValue(window.presetVar.head.head1, 'pk_pcorg')
                    props.cardTable.setValByKeyAndIndex(moudleid, rowIndex, 'pk_pcorg', pcorg)
                    // if (assume_org == null || assume_org.value == null || assume_org.value.trim() == ''){
                    let fydwbm = props.form.getFormItemsValue(window.presetVar.head.head1, 'fydwbm')
                    console.log(fydwbm)
                    props.cardTable.setValByKeyAndIndex(moudleid, rowIndex, 'assume_org', fydwbm)
                    // }
                    // if (assume_dept == null || assume_dept.value == null || assume_dept.value.trim() == ''){
                    let fydeptid = props.form.getFormItemsValue(window.presetVar.head.head1, 'fydeptid')
                    console.log(fydeptid)
                    props.cardTable.setValByKeyAndIndex(moudleid, rowIndex, 'assume_dept', fydeptid)
                    // }
                    // if (bzbm == null || bzbm.value == null || bzbm.value.trim() == ''){
                    let head_bzbm = props.form.getFormItemsValue(window.presetVar.head.head1, 'bzbm')
                    console.log(head_bzbm)
                    props.cardTable.setValByKeyAndIndex(moudleid, rowIndex, 'bzbm', head_bzbm)
                    // }
                    //客商字段
                    const keys = ['customer', 'customer_v', 'hbbm', 'hbbm_v', 'bbhl', 'zzhllx', 'zzhllyrq']
                    let default_values = {}
                    keys.forEach(key => {
                        let headvalue = props.form.getFormItemsValue(window.presetVar.head.head1, key)
                        default_values[key] = headvalue
                    })
                    props.cardTable.setValByKeysAndIndex(moudleid, rowIndex, default_values)


                    //如果第一行有关联的申请单 则加上
                    const pk_keys = ['pk_item', 'pk_mtapp_detail',]
                    const oneRowVal = props.cardTable.getRowsByIndexs(moudleid, 0)[0].values
                    const currentValue = {}
                    pk_keys.forEach(key => {
                        currentValue[key] = oneRowVal[key]
                    })
                    props.cardTable.setValByKeysAndIndex(moudleid, rowIndex, currentValue)

                    // 增行时，本币汇率、汇率类型、汇率来源日期，需根据表头来设置表体其编辑性
                    let bbhlFlag = props.form.getFormItemsDisabled('head', 'bbhl') //表头本币汇率编辑性
                    let zzhllxFlag = props.form.getFormItemsDisabled('head', 'zzhllx') //表头本币汇率类型编辑性
                    let zzhllyrqFlag = props.form.getFormItemsDisabled('head', 'zzhllyrq') //表头本币汇率日期编辑性
                    // 表头中本币种、汇率类型更改后，表体中本币汇率、汇率类型、汇率来源日期需同时控制其编辑性
                    let editkeys = []
                    let unedikeys = []
                    bbhlFlag ? unedikeys.push('bbhl') : editkeys.push('bbhl')
                    zzhllxFlag ? unedikeys.push('zzhllx') : editkeys.push('zzhllx')
                    zzhllyrqFlag ? unedikeys.push('zzhllyrq') : editkeys.push('zzhllyrq')
                    props.cardTable.setEditableByIndex(moudleid, rowIndex, editkeys, true)
                    props.cardTable.setEditableByIndex(moudleid, rowIndex, unedikeys, false)
                }
            },
            ["er_cshare_detail_Export"]: () => {
                let props = this.props
                let tabledata = []
                let formdata = props.createExtCardData(props.meta.getMeta().pageid, "head", ['er_cshare_detail'])
                let rows = this.props.cardTable.getVisibleRows('er_cshare_detail')
                formdata.bodys.er_cshare_detail.rows = rows//过滤表体已经删除的行
                props.meta.getMeta().er_cshare_detail.items.forEach((item) => {
                    if (item.visible && item.visible === true && item.attrcode != "opr") {
                        tabledata.push({ "key": item.attrcode, "label": item.label })
                    }
                })
                formdata.userjson = JSON.stringify(tabledata)
                console.log(formdata)
                const [attrs, el_form] = [
                    {
                        target: '_blank',
                        method: 'POST',
                        enctype: 'application/x-www-form-urlencoded',
                        type: 'hidden',
                        action: '/nccloud/erm/expenseaccount/ExpenseaccountDownLoadAction.do'
                    },
                    document.createElement('form')
                ]
                Object.assign(el_form, attrs)

                const input = document.createElement('input')
                input.type = 'hidden'
                input.name = "data"
                input.value = JSON.stringify(formdata)
                //el_form.append(input);
                el_form.appendChild(input)
                document.body.appendChild(el_form)
                el_form.submit()
                document.body.removeChild(el_form)
                return false
            },
            ["arap_bxbusitem_Export"]: () => {//导出模板
                let props = this.props
                let tabledata = []
                let formdata = props.createExtCardData(props.meta.getMeta().pageid, "head", ['arap_bxbusitem'])
                let rows = this.props.cardTable.getVisibleRows('arap_bxbusitem')
                formdata.bodys.arap_bxbusitem.rows = rows//过滤表体已经删除的行
                props.meta.getMeta().arap_bxbusitem.items.forEach((item) => {
                    if (item.visible && item.visible === true && item.attrcode != "opr") {
                        tabledata.push({ "key": item.attrcode, "label": item.label })
                    }
                })
                formdata.userjson = JSON.stringify(tabledata)
                console.log(formdata)
                const [attrs, el_form] = [
                    {
                        target: '_blank',
                        method: 'POST',
                        enctype: 'application/x-www-form-urlencoded',
                        type: 'hidden',
                        action: '/nccloud/erm/expenseaccount/ExpenseaccountExportAction.do'
                    },
                    document.createElement('form')
                ]
                Object.assign(el_form, attrs)

                const input = document.createElement('input')
                input.type = 'hidden'
                input.name = "data"
                input.value = JSON.stringify(formdata)
                //el_form.append(input);
                el_form.appendChild(input)
                document.body.appendChild(el_form)
                el_form.submit()
                document.body.removeChild(el_form)
                return false
            },
            ["arap_bxbusitem_down"]: () => {
                let props = this.props
                let tabledata = []
                let formdata = props.createExtCardData(props.meta.getMeta().pageid, "head", ['arap_bxbusitem'])
                let rows = this.props.cardTable.getVisibleRows('arap_bxbusitem')
                formdata.bodys.arap_bxbusitem.rows = rows//过滤表体已经删除的行
                props.meta.getMeta().arap_bxbusitem.items.forEach((item) => {
                    if (item.visible && item.visible === true && item.attrcode != "opr") {
                        tabledata.push({ "key": item.attrcode, "label": item.label })
                    }
                })
                formdata.userjson = JSON.stringify(tabledata)
                console.log(formdata)
                const [attrs, el_form] = [
                    {
                        target: '_blank',
                        method: 'POST',
                        enctype: 'application/x-www-form-urlencoded',
                        type: 'hidden',
                        action: '/nccloud/erm/expenseaccount/ExpenseaccountBusitemExportAction.do'
                    },
                    document.createElement('form')
                ]
                Object.assign(el_form, attrs)

                const input = document.createElement('input')
                input.type = 'hidden'
                input.name = "data"
                input.value = JSON.stringify(formdata)
                //el_form.append(input);
                el_form.appendChild(input)
                document.body.appendChild(el_form)
                el_form.submit()
                document.body.removeChild(el_form)
                return false
            }
        }
    }
}

export default tableButtonClick

//打开票夹回调 - 通用事件
function walletClick (props, key) {
    console.log('打开票夹:', key)
    //传票夹列表查询参数
    let param = {}
    param.tradetype = window.presetVar.tradetype
    param.pk_jkbx = props.form.getFormItemsValue("head", "pk_jkbx").value
    param.jkbxr = props.form.getFormItemsValue("head", "jkbxr").value
    param.pk_org = props.form.getFormItemsValue("head", "pk_org").value
    param.tablecode = key
    window.invoiceListQueryParam = param
    this.setState({ showInvoiceWallet: true })
}

//上传发票通用回调
function uploadInvoiceClick (props, key) {
    let param = {}
    param.tradetype = window.presetVar.tradetype
    param.pk_jkbx = props.form.getFormItemsValue("head", "pk_jkbx").value
    param.jkbxr = props.form.getFormItemsValue("head", "jkbxr").value
    param.pk_org = props.form.getFormItemsValue("head", "pk_org").value
    param.tablecode = key
    window.invoiceListQueryParam = param
    this.setState({ showUploadInvoice: true })
}

export { walletClick, uploadInvoiceClick }



/**
 * 导入按钮绑定
 * @param {参数} props 
 */
export function setImportConfig (props) {
    console.log(props)
    let tabledata = []
    let moduleid = 'arap_bxbusitem'
    let formdata = props.createExtCardData(props.meta.getMeta().pageid, "head", [moduleid])
    props.meta.getMeta().arap_bxbusitem.items.forEach((item) => {
        if (item.attrcode != "opr") {
            tabledata.push({ "visible": item.visible, "key": item.attrcode, "label": item.label, "itemtype": item.itemtype, "initialvalue": item.initialvalue && item.initialvalue.value ? item.initialvalue.value : "" })
        }
    })
    formdata.userjson = JSON.stringify(tabledata)
    let config = getExcelImportConfig('/nccloud/erm/expenseaccount/ExpenseaccountImportAction.do', formdata, (resultinfo) => {
        if (resultinfo == 'beginUpload') {
        } else if (resultinfo.success) {
            let rows = props.cardTable.getVisibleRows(moduleid)
            if (rows.length > 0) {
                showWarningDialog('导入', '数据将会被覆盖？', {
                    beSureBtnClick: () => {
                        // let oldRow = props.cardTable.getAllRows(moduleid); 
                        //删行处理   
                        // 遍历得到需要删除行下标
                        console.log("删除行")
                        console.log(rows)
                        let delIndex = rows.map(row => row.viewIndex)
                        props.cardTable.delRowsByIndex(moduleid, delIndex)
                        // rows.map((e)=> {
                        //     e.status='3';
                        // })
                        // headSumHandle(props,rows,'delete',moduleid);       
                        //导入值                                      
                        let exceldata = resultinfo.data.bodys.arap_bxbusitem
                        props.cardTable.setTableData(moduleid, exceldata)
                        //触发金额修改逻辑
                        let newRow = props.cardTable.getVisibleRows(moduleid)
                        newRow.map((e) => {
                            if (e.values.vat_amount.value != null) {
                                e.status = '2'
                                valueChange(props, moduleid, 'vat_amount', e.values.vat_amount.value, e.rowid)
                            }
                        })
                    }
                })
            } else {
                let exceldata = resultinfo.data.bodys.arap_bxbusitem
                props.cardTable.setTableData('arap_bxbusitem', exceldata)
                exceldata.rows.map((e) => {
                    if (e.values.vat_amount.value != null) {
                        e.status = '1'
                        valueChange(props, moduleid, 'vat_amount', e.values.vat_amount.value, e.rowid)
                    }
                })
            }

        }
    })
    props.button.setUploadConfig('arap_bxbusitem_Import', config)

}

export function valueChange (props, moduleid, key, value, rowid) {
    let bodys = window.presetVar.lsBodys
    let bodyarr = []
    let paramdata = {}
    let pagecode = window.presetVar.pagecode
    let hideTable = ['er_cshare_detail']
    bodys.map((one) => {
        if (hideTable.indexOf(one) < 0) {
            bodyarr[bodyarr.length] = one
        }
    })
    paramdata = {
        "value": value,
        "tableid": moduleid,
        "field": key,
        "uistate": 'edit',
        "tradetype": window.presetVar.tradetype,
        "oldvalue": '',
        "pagecode": pagecode,
        "appcode": window.presetVar.appcode,
        "changeRowId": rowid
    }
    let billdata = props.createBodyAfterEventData('20110ETEA_2641_IWEB', "head", bodyarr, moduleid, key, value)
    billdata.card = JSON.parse(JSON.stringify(billdata.card))
    billdata.templetid = props.meta.getMeta().pageid
    billdata.card.head.userjson = JSON.stringify(paramdata)

    requestApi.valueChange({
        data: billdata.card,
        success: (data) => {
            beforeUpdatePage(props)
            //设置表头数据
            let filterdata = requestApi.filterDatas(data.head[presetVar.head.head1])
            // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
            // props.form.setAllFormValue({[presetVar.head.head1]: filterdata});
            updataFormData(props, presetVar.head.head1, filterdata)
            // BTM 性能优化，变更页面数据更新方法
            window.presetVar.reloadHead = filterdata
            //设置表体数据
            // props.cardTable.setTableData(presetVar.body.body1, data.data.body[presetVar.body.body1]);
            let filterbodydatas = requestApi.filterDatas(data.bodys[moduleid])
            if (filterbodydatas && filterbodydatas.rows) {
                let rows = []
                for (let i = 0; i < filterbodydatas.rows.length; i++) {
                    if (filterbodydatas.rows[i].values && filterbodydatas.rows[i].values.tablecode && filterbodydatas.rows[i].values.tablecode.value == moduleid) {
                        rows[rows.length] = filterbodydatas.rows[i]
                    } else if (moduleid === 'er_cshare_detail') { //分摊没有tablecode，不走过滤
                        rows[rows.length] = filterbodydatas.rows[i]
                    }
                }
                filterbodydatas.rows = rows
            }
            // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
            // props.cardTable.setTableData(moduleid,filterbodydatas);
            updatacardTableData(props, moduleid, filterbodydatas)
            // BTM 性能优化，变更页面数据更新方法
            // let billdatas = props.createExtCardData(window.presetVar.pageId, window.presetVar.head.head1,bodyarr);
            // requestApi.handleLoadDataResDada(props.meta.getMeta(), {data:billdatas},props,moduleid);

            //fix: setTableDataWithResetInitValue会导致表体的index丢失
            let currentIndex = props.cardTable.getCurrentIndex(moduleid)
            props.cardTable.updateDataByRowId(moduleid, filterbodydatas)
            props.cardTable.focusRowByIndex(moduleid, currentIndex)
            // props.cardTable.setTableData(moduleid,filterbodydatas);
            updatePage(props, presetVar.head.head1, [moduleid])
        }
    })
}

/**
 * 参照系统，汇总表头金额
 * @param {参数} props 
 */
export function headSumHandle (props, args, type, areaId) {
    //需要汇总的金额字段
    let bodyFieldArr = ["amount", "ybje", "cjkybje", "zfybje", "hkybje", "bbje",
        "cjkbbje", "zfbbje", "hkbbje", "globalbbje", "globalcjkbbje", "globalzfbbje", "globalhkbbje",
        "groupbbje", "groupcjkbbje", "groupzfbbje", "grouphkbbje", "tax_amount", "orgtax_amount", "grouptax_amount", "globaltax_amount",
        "tni_amount", "orgtni_amount", "grouptni_amount", "globaltni_amount", "vat_amount", "orgvat_amount", "groupvat_amount", "globalvat_amount"]
    let changeHeadItem = {}
    let head1 = 'head'
    bodyFieldArr.forEach((bodyField) => {//循环字段
        let totalMny = 0
        let headField = bodyField == "amount" ? "total" : bodyField//total字段特殊处理
        let scale = props.form.getFormItemsValue(head1, headField).scale//取精度
        for (let name in window.presetVar.body) {//循环业务页签
            let areaId = window.presetVar.body[name]
            if (areaId !== 'accrued_verify' && areaId !== 'er_bxcontrast' && areaId !== 'er_cshare_detail') {
                let rows = props.cardTable.getVisibleRows(areaId)
                for (let i in rows) {
                    if (
                        rows[i].values[bodyField] != undefined &&
                        rows[i].values[bodyField] != null &&
                        rows[i].values[bodyField].value != null
                    ) {
                        totalMny += +rows[i].values[bodyField].value * Math.pow(10, scale) //汇总
                    }
                }
            }
        }
        totalMny = totalMny / Math.pow(10, scale)
        changeHeadItem[headField] = { scale: scale, value: totalMny, display: null }
    })
    props.form.setFormItemsValue(head1, changeHeadItem)
    // 新增其他页签删除后发票页签联动删除逻辑
    if (type && type == 'delete') {
        let pk_erminvoice = args[0].values.pk_erminvoice.value
        let invoice_Detail = props.cardTable.getVisibleRows('invoice_Detail')
        const bodyDetailRows = props.cardTable.getVisibleRows(areaId)

        if (
            bodyDetailRows.some((item) => {
                return item.values.pk_erminvoice.value === pk_erminvoice
            })
        ) {
            return
        }

        let bxToInvoice = window.presetVar.bxToInvoice
        let invioces = bxToInvoice && bxToInvoice[pk_erminvoice]
        let goalInvioce = [] //符合的发票
        invioces && invioces.forEach((itemInvoice, index) => {
            let oriTrs = []
            oriTrs = invoice_Detail.filter((item) => {
                return item.values.pk_erminvoice.value === itemInvoice
            })
            goalInvioce = [...goalInvioce, ...oriTrs]
        })

        if (goalInvioce.length) {
            goalInvioce.forEach((item) => {
                props.cardTable.delRowByRowId('invoice_Detail', item.rowid)
            })

        }
    }
}
